package com.example.redissession.dlm;

import com.example.redissession.config.FastJson2JsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author: cph
 * @date: 2022/3/18 17:57
 */
@Configuration
public class RedisConfig {

    @Bean("unlock")
    public RedisScript<Boolean> unlockScript() {
        Resource script = new ClassPathResource("unlock.lua");
        return RedisScript.of(script, Boolean.class);
    }

    @Bean
    public RedisSerializer fastjson2JsonRedisSerializer() {
        return new FastJson2JsonRedisSerializer<>(Object.class);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory factory, RedisSerializer fastjson2JsonRedisSerializer) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(fastjson2JsonRedisSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(fastjson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}
